<template>
    <div class="lilith-chat-textarea">
        <el-input :model-value="text" type="textarea" :placeholder="placeholder" @input="$emit('update:text', $event)"
            :rows="rows"></el-input>
        <div class="textarea-handle" v-if="robot">
            <el-button class="FormBtn" @click="showRobot" round><el-icon class="icon">
                    <Avatar />
                </el-icon><span class="txt">AI优化</span></el-button>
        </div>

        <!-- 选择ai -->
        <el-drawer custom-class="chat-drawer" v-model="showRobotDialog" :destroy-on-close="false"
            :style="{ minWidth: '432px' }" :z-index="2100" @close="closeChoseItem">
            <div class="chose-chat">
                <div class="lilith-chat-item" @click="choseRedBook">
                    <div class="item-img-box"><img :src="redBookImg" alt=""> </div>
                    <div>生成小红书爆款文案</div>
                </div>
                <div class="lilith-chat-item" @click="choseTikTok">
                    <div class="item-img-box"><img :src="tiktokImg" alt=""></div>
                    <div>生成抖音爆款文案</div>
                </div>
                <div class="lilith-chat-item" @click="choseFrend">
                    <div class="item-img-box"><img :src="frendImg" alt=""></div>
                    <div>生成朋友圈爆款文案</div>
                </div>
                <text>
                    AI可以根据你的图片描述，生成符合平台规则的文案 <br>
                    你也可以直接发送消息AI将为你服务
                </text>
            </div>
        </el-drawer>
        <!-- 聊天框 -->
        <el-drawer custom-class="chat-drawer" v-model="showRobotDialogByChose" :title="aiName" :destroy-on-close="false"
            :style="{ minWidth: '432px' }" :z-index="2100">
            <div class="lilith-chat">

                <div class="chat-context" ref="chatContext">
                    <div v-for="(v, i) in chatList" :key="'chattext' + i" v-show="v.robotId == robotId">
                        <div class="chattext-item right">
                            <div class="chattext">
                                {{ v.question || '' }}
                            </div>
                        </div>

                        <div class="chattext-item left" v-if="v.answer">
                            <div class="chat-avatar">
                                <div class="lilith-info">
                                    <img :src="aiPic" /><span>{{ aiName }}</span>
                                </div>
                            </div>
                            <div class="chattext" v-html="replaceHtml(v.answer || '')">
                            </div>
                            <div class="chat-handle">
                                <el-button @click="refreshQuestion" :data-text="v.answer" size="small">
                                    <el-icon class="icon">
                                        <Refresh />
                                    </el-icon>
                                    <span class="txt">重新生成</span>
                                </el-button>
                                <el-button @click="copyText" :data-text="v.answer" size="small">
                                    <el-icon>
                                        <DocumentCopy />
                                    </el-icon>
                                    <span class="txt">复制文本</span>
                                </el-button>
                            </div>
                        </div>
                    </div>

                    <div class="loading-chat" v-if="loading">
                        <div></div>
                        <div></div>
                        <div></div>
                    </div>
                </div>

                <div class="chat-input-wrap">
                    <el-button class="btn-clear" @click="clear">
                        <i class="iconfont icon-noread"></i>
                        <!-- <el-icon class="icon">
                            <DocumentAdd />
                        </el-icon></el-button> -->
                    </el-button>
                    <el-input class="textarea" v-model="chatTxt" type="textarea" placeholder="请输入您的问题并展开讨论" rows="1"  @keyup.enter.native="sendText"/>
                    <el-button class="btn-send" @click="sendText"><el-icon class="icon">
                            <Avatar />
                        </el-icon><span class="txt">提问</span></el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
.item-img-box {
    width: 20%;
    border-right: 1px solid #eee;
    margin-right: 20px;
}

.lilith-chat-textarea .chat-input-wrap {
    .el-textarea__inner {
        border-radius: 16px;
    }
}

.chattext {
    white-space: normal;
}

.chattext img {
    height: 16px !important;
    width: auto !important;
}

.chattext>div {
    display: block !important;
    vertical-align: baseline;
}
</style>
<style lang="scss" scoped>
.lilith-chat-item {
    box-shadow: 0 0 4px 1px #eee;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 20px;
    display: flex;
    align-items: center;
}

.lilith-chat-item img {
    width: 35%;
}

.lilith-chat-textarea {
    width: 100%;
}

.textarea-handle {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 8px;
}

.lilith-chat {
    position: relative;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.chose-chat {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    text {
        font-size: 12px;
    }
}

.chat-avatar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-right: 24px;

    .lilith-info {
        display: flex;
        align-items: center;
    }

    img {
        width: 22px;
        height: 22px;
        border-radius: 999px;
        margin-right: 4px;
    }
}

.chat-context {
    padding-right: 12px;
    overflow-y: auto;
}

.chattext-item {
    text-align: left;
    margin-bottom: 12px;

    .chattext {
        display: inline-block;
        padding: 8px 12px;
        line-height: 1.5;
        text-align: left;
        border-radius: 4px;
        background: #f6f6f6;
        margin-right: 24px;
    }

    .chat-handle {
        text-align: left;
        margin-right: 24px;
    }

    &.right {
        text-align: right;

        .chat-avatar {
            justify-content: flex-end;
            margin-right: 0;
        }

        .chattext {
            background: #d4e9ff;
            margin-right: 0;
            margin-left: 24px;
            white-space: normal;
        }
    }
}

.chattext img {
    height: 16px !important;
    width: auto !important;
}

.chattext>div {
    display: block !important;
    vertical-align: top;
    line-height: 16px;
}

.chat-input-wrap {
    display: flex;
    padding: 12px 0;
    background: #ffffff;
    line-height: 16px;

    .btn-clear {
        margin-right: 8px;
        height: 100%;
        width: 32px;
        height: 32px;
        border-radius: 16px;
        background: #21213c;
        color: #fff;
        border: none;
    }

    .btn-send {
        height: 100%;
        margin-left: 8px;
        border-radius: 16px;
        color: #fff;
        background: #21213c;
        border: none;
    }
}

.loading-chat {
    >div {
        display: inline-block;
        width: 15px;
        height: 15px;
        border-radius: 100%;
        margin: 2px;
        background-color: #ccc;
        -webkit-animation-fill-mode: both;
        animation-fill-mode: both;

        &:nth-child(1) {
            -webkit-animation: ball-scale 0.75s 0.12s infinite cubic-bezier(.2, .68, .18, 1.08);
            animation: ball-scale 0.75s 0.12s infinite cubic-bezier(.2, .68, .18, 1.08);
        }

        &:nth-child(2) {
            -webkit-animation: ball-scale 0.75s 0.24s infinite cubic-bezier(.2, .68, .18, 1.08);
            animation: ball-scale 0.75s 0.24s infinite cubic-bezier(.2, .68, .18, 1.08);
        }

        &:nth-child(3) {
            -webkit-animation: ball-scale 0.75s 0.36s infinite cubic-bezier(.2, .68, .18, 1.08);
            animation: ball-scale 0.75s 0.36s infinite cubic-bezier(.2, .68, .18, 1.08);
        }
    }
}

@keyframes ball-scale {
    0% {
        -webkit-transform: scale(1);
        transform: scale(1);
    }

    50% {
        -webkit-transform: scale(0.5);
        transform: scale(0.5);
        opacity: 0.7;
    }

    100% {
        -webkit-transform: scale(1);
        transform: scale(1);
        opacity: 1;
    }
}
</style>
<script>
import WebRequest from '../../unit/request.js'
export default {
    name: 'LilithChat',
    components: {},
    props: {
        rows: 6,
        text: '',
        // 占位内容
        placeholder: {
            type: String,
            default: ''
        },
        // 是否显示机器人选项
        robot: {
            type: Boolean,
            default: false
        },
        isChatViewVisible: {
            type: Boolean,
            default: false
        }
    },
    emits: ['update:text'],
    data() {
        return {
            // 70 小红书爆文专家
            // 24 爆裂朋友圈	
            // 5 狂暴种草	
            robotId: 79,//79:AI生图提示词助手, 52:莉莉丝	,
            testToken: 'nfaxNJJF5oLZ-gPCn3d0J3oucZ636SGY_1701079527',
            chatTxt: '',              // 聊天文本
            refreshQuestionData:'',    //刷新后的聊天文本
            showRobotDialog: false,   // 是否显示弹窗
            Authorization: "",        //校验
            liliRobot: null,          // 机器人
            chatId: null,             // 对话ID
            chatList: [],             // 对话列表
            chatArr: [],               //可用聊天机器人
            loading: false,           // 是否加载中
            isFirstOpen: true,
            showRobotDialogByChose: false,
            aiName: '莉莉丝',
            // 朋友圈图片
            frendImg: "",
            //抖音图片
            tiktokImg: "",
            // 小红书图片
            redBookImg: ''
        }
    },
    mounted() {
        // 设置测试token
        WebRequest.Lili.token = this.testToken
        this.queryChat()
    },
    // 子组件中的 watch 钩子
    watch: {
        isChatViewVisible(newVal) {
            console.log(newVal, 'newVal');
            if (newVal) {
                this.showRobotDialog = true;
            } else {
                this.showRobotDialog = false;
            }
        }
    },

    methods: {
        // 刷新返回的问题
        refreshQuestion(){
            this.chatTxt=this.refreshQuestionData
            this.sendText()
        },
        // 复制
        copyText(event) {
            const textToCopy = event.currentTarget.getAttribute('data-text');

            // 创建一个临时的textarea元素
            const textarea = document.createElement('textarea');
            textarea.value = textToCopy;
            textarea.setAttribute('readonly', '');
            textarea.style.position = 'absolute';
            textarea.style.left = '-9999px';

            // 将textarea添加到DOM中
            document.body.appendChild(textarea);

            // 选中文本并复制到剪贴板
            textarea.select();
            document.execCommand('copy');

            // 删除临时textarea
            document.body.removeChild(textarea);
            this.$message({
                message: '复制文案成功',
                type: 'success',
            })
            // 复制成功的处理逻辑
            console.log('文本已成功复制！');
        },
        // 关闭选择 机器人 分类
        closeChoseItem() {
            console.log('closeChoseItem');
            this.$emit("closeChoseItem", false)
        },
        // 创建机器人
        async createChatPeople(id) {
            try {
                let res = await WebRequest.Lili.AddChat(id)
                console.log(res, 'add res');
            } catch (error) {
                console.log(error)
            }
        },
        // 檢查id是否存在，不存在則創建
        checkAndFetchData(id) {
            console.log('查找');
            const foundItem = this.chatArr.find((item) => {
                return item.chatId == id; // 使用双等号进行类型转换的比较
            });
            console.log(foundItem, id, '????????????');
            if (!foundItem) {
                this.createChatPeople(id)
            } else {
                console.log("ID already exists in the array:", foundItem);
            }
        },

        // 查询所有机器人id
        async queryChat() {
            try {
                let People = await WebRequest.Lili.People()
                console.log(People, 'People');
                People.data.data.map((item) => {
                    this.chatArr.push({
                        chatId: item.people.id,
                        name: item.people.name,
                        desc: item.people.desc
                    })
                })
                console.log(this.chatArr);
            } catch (error) {
                console.log(error)
            }
        },
        // 选择小红书
        choseRedBook() {
            this.aiName = '小红书'
            this.aiPic = this.redBookImg
            this.robotId = 70
            this.checkAndFetchData(this.robotId)
            this.showRobotDialogByChose = true
        },
        // 选择抖音
        choseTikTok() {
            this.aiName = '抖音'
            this.aiPic = this.tiktokImg
            this.robotId = 47
            this.checkAndFetchData(this.robotId)
            this.showRobotDialogByChose = true
        },
        // 选择朋友圈
        choseFrend() {
            this.aiName = '朋友圈'
            this.aiPic = this.frendImg
            this.robotId = 51
            this.checkAndFetchData(this.robotId)
            this.showRobotDialogByChose = true
        },
        // 清除会话
        async clear() {
          this.showRobot('clear');
        },
        autoSend() {
            if (this.isFirstOpen && this.text && this.text != '') {
                console.log("is first open")
                this.isFirstOpen = false
                this.clear();
                let sendTxt = this.text;
                this.sendText(null, sendTxt);
            }
        },
        // 显示AI助手
        showRobot(data) {
            if (!this.liliRobot) {
                setTimeout(async () => {
                    try {
                        // 获取机器人
                        this.liliRobot = await WebRequest.Lili.getView({ id: this.robotId })
                        // 获取对话id和对话列表
                        let peopleData = await WebRequest.Lili.getChatPeople({ chat_id: 0, model_id: this.robotId })
                        console.log(peopleData,'peopleData', peopleData.data.data.chat_id);
                        this.chatId = peopleData.data.data.chat_id
                        this.chatList = peopleData.data.data.data || []
                        this.scrollBottom()
                        this.autoSend()
                        if(data='clear'){
                            let res =await WebRequest.Lili.Clear({ chat_id: this.chatId })
                            console.log(res,this.chatId,'chatIdchatId',data);
                        }
                    } catch (error) {
                        console.log(error)
                    }
                }, 1)
            } else {
                this.autoSend()
            }
            this.showRobotDialog = true
        },

        // 发送文本
        async sendText(e, txt) {
            if(this.chatTxt=='\n'){
                this.chatTxt=''
                 this.$message({
                message: '问题内容不能为空',
                type: 'error',
            })
            return

            }
            // console.log(this.chatTxt=='',this.chatTxt=='\n','this.chatTxt');
            if (this.loading || ((!txt || txt == '') && (!this.chatTxt || this.chatTxt == ''))) {
                console.log('buwen');
                return
            }
            try {
                let text = this.chatTxt
                if (txt) {
                    text = txt
                }
                // 创建问题数据
                // let qItem = {
                //     question: text,
                //     answer: null,
                // }
                this.loading = true
                this.chatList.push({ robotId: this.robotId, aiName: this.aiName, question: text })
                this.scrollBottom(100, () => {
                    //this.chatTxt = this.text
                    this.refreshQuestionData=this.chatTxt
                    this.chatTxt = ""
                })
                // 提交问题
                let res = await WebRequest.Lili.postChat({
                    chat_id: this.chatId,
                    prompt: text,
                    model_id: this.robotId,
                    type: 1,
                    use_model: 3
                })
                if (res.status == 200) {
                    let session_id = res.data.data.session_id
                    // 获取问题答案
                    let answer = await WebRequest.Lili.getAnswer({ session_id })
                    // 添加答案
                    if (answer.data) {
                        this.chatList[this.chatList.length - 1].answer = answer.data
                        this.scrollBottom()
                        console.log(this.chatList, 'this.chatList');
                        this.loading = false
                    }
                }
            } catch (error) {
                this.loading = false
                console.log(error)
            }
        },

        replaceHtml(text) {
            return text.replace(/\n/g, '</br>')
        },

        // 采用文本
        adoptText(e) {
            let text = e.currentTarget.dataset.text || ''
            this.$emit('update:text', text)
            this.showRobotDialog = false
        },

        // 滚动到底部
        scrollBottom(time = 100, callBack) {
            setTimeout(() => {
                let $cct = this.$refs['chatContext']
                let height = $cct.scrollHeight
                $cct.scrollTop = height
                callBack && callBack()
            }, time)
        },
    }
}
</script>